<template>
	<view class="content-box">
		<view class="detail-info">
			<view class="detail">
				<!-- 课程信息 -->
				<u-cell-group :title="lessonInfo.Title||''">
					<u-cell-item title="老师" :value="lessonInfo.Name" :arrow="false"></u-cell-item>
					<u-cell-item title="日期" :value="lessonDate" :arrow="false"></u-cell-item>
				</u-cell-group>
				<!-- 统计信息 -->
				<u-cell-group :title="cntAllText">
					<u-cell-item title="短句学习统计" @click="handleOpenSentence" :value="cntSentence.length+'个'"
						:arrow-direction="sentenceOpen"></u-cell-item>
					<view v-if="sentenceOpen==='down'" style="margin-left: 10px;margin-right: 10px;">
						<view @click="playMp3(item.Audio)" v-for="item in cntSentence" :key="item.WordId"
							style="display: flex; flex-flow: column; width:100%; font-size: var(--text-14); padding: 15rpx; border-bottom: 0.1rpx solid #777; padding-bottom: 20rpx;">
							<view>{{item.SentenceEn}}</view>
							<view>{{item.SentenceCn}}</view>
						</view>
					</view>
					<u-cell-item title="8-9 阶生词" @click="handleOpen1" :value="cntWord1.length+'个'"
						:arrow-direction="cnt1Open"></u-cell-item>
					<view v-if="cnt1Open==='down'" style="margin-left: 10px;margin-right: 10px;">
						<view @click="playMp3(item.MP3)" v-for="item in cntWord1" :key="item.WordId"
							style="display: flex; width:100%; font-size: var(--text-14); padding: 15rpx; border-bottom: 0.1rpx solid #777; padding-bottom: 20rpx;">
							<view style="flex: 1;">
								{{item.Word}}
							</view>
							<view style="flex: 1;">
								<view>
									{{item.Mean}}
								</view>
							</view>
							<view style="width:100rpx; text-align: center;"
								:class="(item.PrevLostLvSnapshot>item.LostLv)?'down':'up'">
								<text
									v-if="item.PrevLostLvSnapshot!=item.LostLv">{{(item.PrevLostLvSnapshot/2).toFixed(0)}}<text
										style="font-size: var(--text-12);">→</text></text>
								<text>{{(item.LostLv/2).toFixed(0)}}</text>
							</view>
						</view>
					</view>
					<u-cell-item title="5-7 阶生词" @click="handleOpen2" :value="cntWord2.length+'个'"
						:arrow-direction="cnt2Open"></u-cell-item>
					<view v-if="cnt2Open==='down'" style="margin-left: 10px;margin-right: 10px;">
						<view @click="playMp3(item.MP3)" v-for="item in cntWord2" :key="item.WordId"
							style="display: flex; width:100%; font-size: var(--text-14); padding: 15rpx; border-bottom: 0.1rpx solid #777; padding-bottom: 20rpx;">
							<view style="flex: 1;">
								{{item.Word}}
							</view>
							<view style="flex: 1;">
								<view>
									{{item.Mean}}
								</view>
							</view>
							<view style="width:100rpx; text-align: center;"
								:class="(item.PrevLostLvSnapshot>item.LostLv)?'down':'up'">
								<text
									v-if="item.PrevLostLvSnapshot!=item.LostLv">{{(item.PrevLostLvSnapshot/2).toFixed(0)}}<text
										style="font-size: var(--text-12);">→</text></text>
								<text>{{(item.LostLv/2).toFixed(0)}}</text>
							</view>
						</view>
					</view>
					<u-cell-item title="1-4 阶生词" @click="handleOpen3" :value="cntWord3.length+'个'"
						:arrow-direction="cnt3Open"></u-cell-item>
					<view v-if="cnt3Open==='down'" style="margin-left: 10px;margin-right: 10px;">
						<view @click="playMp3(item.MP3)" v-for="item in cntWord3" :key="item.WordId"
							style="display: flex; width:100%; font-size: var(--text-14); padding: 15rpx; border-bottom: 0.1rpx solid #777; padding-bottom: 20rpx;">
							<view style="flex: 1;">
								{{item.Word}}
							</view>
							<view style="flex: 1;">
								<view>
									{{item.Mean}}
								</view>
							</view>
							<view style="width:100rpx; text-align: center;"
								:class="(item.PrevLostLvSnapshot>item.LostLv)?'down':'up'">
								<text
									v-if="item.PrevLostLvSnapshot!=item.LostLv">{{(item.PrevLostLvSnapshot/2).toFixed(0)}}<text
										style="font-size: var(--text-12);">→</text></text>
								<text>{{(item.LostLv/2).toFixed(0)}}</text>
							</view>
						</view>
					</view>
					<u-cell-item title="熟悉词" @click="handleOpen4" :value="cntWord4.length+'个'"
						:arrow-direction="cnt4Open"></u-cell-item>
					<view v-if="cnt4Open==='down'" style="margin-left: 10px;margin-right: 10px;">
						<view @click="playMp3(item.MP3)" v-for="item in cntWord4" :key="item.WordId"
							style="display: flex; width:100%; font-size: var(--text-14); padding: 15rpx; border-bottom: 0.1rpx solid #777; padding-bottom: 20rpx;">
							<view style="flex: 1;">
								{{item.Word}}
							</view>
							<view style="flex: 1;">
								<view>
									{{item.Mean}}
								</view>
							</view>
						</view>
					</view>
				</u-cell-group>
				<u-cell-group title="课程内容" v-if="visibleEvaluate">
					<u-cell-item @click="downloadExcel" title="打印"></u-cell-item>
				</u-cell-group>
				<!-- 评价信息 -->
				<u-cell-group title="评价" v-if="visibleEvaluate">
					<u-cell-item title="对老师的评价" :arrow="false">
						<u-rate v-if="hasToTeacherEvaluateScore" :count="5" disabled
							v-model="ToTeacherEvaluateScore"></u-rate>
						<view v-if="hasToTeacherEvaluateScore">{{evaluateToTeacherContent}}</view>
						<u-tag v-else-if="isStudent" @click="handleEvaluate(1)" text="评价" mode="light" />
						<text v-else>暂无</text>
					</u-cell-item>
					<u-cell-item title="对学生的评价" :arrow="false">
						<u-rate v-if="hasToStudentEvaluateScore" :count="5" disabled
							v-model="ToStudentEvaluateScore"></u-rate>
						<view v-if="hasToStudentEvaluateScore">{{evaluateToStudentContent}}</view>
						<u-tag v-else-if="isTeacher" @click="handleEvaluate(2)" text="评价" mode="light" />
						<text v-else>暂无</text>
					</u-cell-item>
				</u-cell-group>
			</view>
		</view>
		<view v-if="Type=='count'" style="width:90%; margin:10px auto;">
			<view style="font-size: var(--text-12); color:#777; text-align: center;">
				<text>最佳复习时间:</text>
				<text v-for="(item,index) in wpList">
					{{item.title}}:{{item.count}}个
				</text>
			</view> 
			<view style="margin:10px;">
				<u-button @click="yynextles" class="next-btn w-full" type="warning" :plain="true">
					<view class="next-text">预约下一堂课</view>
				</u-button>
			</view>
			<view style="font-size: 12px; color:#777; text-align: center;"> 
				<view>
					<text v-if="reviewfirst" style="color:#000;font-size:var(--text-14);">系统建议优先复习,</text>
					<text v-else="reviewfirst" style="color:#000;font-size:var(--text-14);">系统建议优先学新,</text>
					<text>请根据具体情况预约下一节课</text>
				</view> 
			</view>
		</view>
		<ClassStudentExpand :stid="lessonInfo.StudentAccountId" :wplist="wpList"></ClassStudentExpand>
		<u-popup v-model="visibleEvaluateDia" mode="top" height="600rpx" z-index="998">
			<view style="margin-top: 145rpx;padding: 50rpx; display: flex; flex-flow: column; align-items: flex-start;">
				<view class="mb-5rpx">评价分数</view>
				<u-rate :count="5" v-model="EvaluateScore"></u-rate>
				<u-input v-model="EvaluateContent" type="textarea" class="w-full mt-16rpx" :border="true"
					placeholder="请输入评价内容" :height="100" :auto-height="true" />
				<u-button class="mt-30rpx w-full" type="primary" @click="handleSetEvaluate">提交</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script lang="ts" setup>
	import { onLoad, onReady } from '@dcloudio/uni-app';
	import { ref, onMounted, watch, computed } from 'vue';
	import { useStudyStore } from '@/store/study';
	import { useSoundEffect } from '@/common/hooks';
	import { useClassStore } from '@/store/class';
	import { OT, dateFormat, ktlapi, ktluser, lodash } from '@/utils';
	import ClassStudentExpand from '@/pages/tabbar/class/modules/class-student-expand.vue';


	/** 步骤：最终结果反馈 */
	defineOptions({
		name: 'step-final-result',
		inheritAttrs: false
	});

	const classStore = useClassStore();
	const studyStore = useStudyStore();
	const { playMp3 } = useSoundEffect();
	const emit = defineEmits(['next', 'module-event']);
	const props = defineProps({
		lessonUuid: {
			type: String,
			default: ''
		}
	});

	const isTeacher = ref(false);
	const isStudent = ref(false);
	const Type = ref<string>('count');
	const LessonUUID = ref<any>(props.lessonUuid);
	const lessonInfo = ref<any>({});
	const evaluateList = ref<any[]>([]);
	const remeberList = ref<any[]>([]);

	const lessonDate = ref<string>('');
	const cntAllText = ref<string>('');

	const cntWord1 = ref<any[]>([]);
	const cntWord2 = ref<any[]>([]);
	const cntWord3 = ref<any[]>([]);
	const cntWord4 = ref<any[]>([]);
	const cntSentence = ref<any[]>([]);

	const cnt1Open = ref<string>('right');
	const cnt2Open = ref<string>('right');
	const cnt3Open = ref<string>('right');
	const cnt4Open = ref<string>('right');
	const sentenceOpen = ref<string>('right');
	const isReview = ref(false);
	const toType = ref(null);
	const visibleEvaluateDia = ref(false);
	const EvaluateScore = ref(0);
	const EvaluateContent = ref('');
	const evaluateToTeacherContent = ref<string>('');
	const evaluateToStudentContent = ref<string>('');
	const ToTeacherEvaluateScore = ref(null);
	const ToStudentEvaluateScore = ref(null);
	const reviewfirst = ref(false);
	const wpList = ref([{
		"title": "已过期",
		"tp": 0,
		"count": 0
	},
	{
		"title": "24小时内",
		"tp": 1,
		"count": 0
	}, {
		"title": "更长时间",
		"tp": 2,
		"count": 0
	}]);



	const visibleEvaluate = computed(() => {
		return Type.value !== 'count';
	})
	const hasToTeacherEvaluateScore = computed(() => ![undefined, null].includes(ToTeacherEvaluateScore.value));
	const hasToStudentEvaluateScore = computed(() => ![undefined, null].includes(ToStudentEvaluateScore.value));

	function downloadExcel() {
		uni.showLoading({
			title: '正在生成',
			mask: true
		});
		ktlapi({
			apiurl: "Excel/LessonResult",
			data: {
				LessonUUID: LessonUUID.value
			}
		}).then((res) => {
			uni.hideLoading();
			console.log(res);
			if (res.status) {
				uni.showLoading({
					title: '下载中..',
					mask: true
				});

				// #ifdef MP-WEIXIN
				uni.downloadFile({
					url: 'https://nx5.abc5g.com' + res.data, //仅为示例，并非真实的资源
					success(res) {
						uni.hideLoading();
						// 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
						if (res.statusCode === 200) {
							console.log(res.tempFilePath);
							uni.openDocument({
								filePath: res.tempFilePath,
								success: function (res) {
									console.log('打开文档成功')
								}
							})
						}
					}
				})
				// #endif
				// #ifdef H5
				// 浏览器环境
				window.location = "https://nx5.abc5g.com" + res.data;
				uni.hideLoading();
				// #endif
			} else {
				uni.showToast({
					title: '没有学习数据',
					icon: "error",
					duration: 2000
				});
			}
		});

	}

	function handleOpenSentence() {
		if (sentenceOpen.value === 'right') {
			sentenceOpen.value = 'down';
		} else {
			sentenceOpen.value = 'right';
		}
	}

	function yynextles() {
		console.log('yy');
		classStore.initStudentData();
		classStore.Pop = true;
	}

	function handleOpen1() {
		if (cnt1Open.value === 'right') {
			cnt1Open.value = 'down';
		} else {
			cnt1Open.value = 'right';
		}
	}
	function handleOpen2() {
		if (cnt2Open.value === 'right') {
			cnt2Open.value = 'down';
		} else {
			cnt2Open.value = 'right';
		}
	}
	function handleOpen3() {
		if (cnt3Open.value === 'right') {
			cnt3Open.value = 'down';
		} else {
			cnt3Open.value = 'right';
		}
	}
	function handleOpen4() {
		if (cnt4Open.value === 'right') {
			cnt4Open.value = 'down';
		} else {
			cnt4Open.value = 'right';
		}
	}

	const getToEvaluateScore = (item : any) => {
		if (item && item.Type) {
			return item.EvaluateScore
		}
		return null
	}

	function handleEvaluate(to : number) {
		toType.value = to;
		visibleEvaluateDia.value = true;
	}
	function handleSetEvaluate() {
		ktlapi({
			action: 'Cus_SetLessonEvaluate',
			data: {
				LessonUUID: LessonUUID.value,
				Score: EvaluateScore.value,
				EvaluateContent: EvaluateContent.value,
				Type: toType.value
			}
		}).then(() => {
			if (toType.value === 1) {
				ToTeacherEvaluateScore.value = EvaluateScore.value;
			}
			if (toType.value === 2) {
				ToStudentEvaluateScore.value = EvaluateScore.value;
			}
			visibleEvaluateDia.value = false;
		})
	}

	function initRole() {
		if (ktluser.hasRole(2)) {
			isTeacher.value = true;
			isStudent.value = false;
		} else if (ktluser.hasRole([3, 4]) && !ktluser.hasRole(2)) {
			isTeacher.value = false;
			isStudent.value = true;
		}
	}

	function initData() {
		console.log(LessonUUID.value);
		if (!LessonUUID.value) {
			return
		}
		var proc = '';
		if (isReview.value) {
			proc = 'Cus_GetLessonFinalResult_Review'
		} else {
			proc = "Cus_GetLessonFinalResult";
		}
		ktlapi({
			apiurl: OT.CommandSet,
			action: proc,
			data: {
				LessonUUID: LessonUUID.value
			}
		}).then((data : any) => {
			// console.log(data)
			lessonInfo.value = lodash.get(data, 'data.tables[0].table[0]', {});
			evaluateList.value = lodash.get(data, 'data.tables[1].table', []);
			remeberList.value = lodash.get(data, 'data.tables[2].table', []);
			if (lessonInfo.value.StartTime) {
				const StartTime = lessonInfo.value.StartTime.split(':').filter((_item : string, index : number) => index < 2).join(":")
				const EndTime = lessonInfo.value.EndTime.split(':').filter((_item : string, index : number) => index < 2).join(":")
				lessonDate.value = dateFormat(lessonInfo.value.StudyDay) + ' ' + StartTime + '-' + EndTime;
			}

			cntSentence.value = [...new Set(remeberList.value.map((item : any) => item.SentenceSnapshot))]
				.map((item : any) => {
					if (item) {
						return JSON.parse(item)
					}
					return {}
				});
			cntAllText.value = '本次课程共涉及' + cntSentence.value.length + '个句子，' + remeberList.value.length + '个词汇';

			cntWord1.value = remeberList.value.filter(item => item.LostLv > 14);
			cntWord2.value = remeberList.value.filter(item => item.LostLv > 8 && item.LostLv <= 14);
			cntWord3.value = remeberList.value.filter(item => item.LostLv > 0 && item.LostLv <= 8);
			cntWord4.value = remeberList.value.filter(item => item.LostLv === 0);

			const evaluateToTeacherInfo : any = evaluateList.value.find(item => item.Type === 1);
			const evaluateToStudentInfo : any = evaluateList.value.find(item => item.Type === 2);
			ToTeacherEvaluateScore.value = getToEvaluateScore(evaluateToTeacherInfo);
			ToStudentEvaluateScore.value = getToEvaluateScore(evaluateToStudentInfo);

			if (evaluateToTeacherInfo) {
				evaluateToTeacherContent.value = evaluateToTeacherInfo.Evaluate;
			} else {
				evaluateToTeacherContent.value = '暂无';
			}
			if (evaluateToStudentInfo) {
				evaluateToStudentContent.value = evaluateToStudentInfo.Evaluate;
			} else {
				evaluateToStudentContent.value = '暂无';
			}
		})

		if (Type.value == 'count') {
			ktlapi({
				action: "RBSTimeComm",
				data: {
					UUID: LessonUUID.value
				}
			}).then((data : any) => {
				for(var i=0;i<wpList.value.length;i++){ 
					for(var j=0;j<data.data.length;j++){
						if(wpList.value[i]["tp"] == data.data[j]["TP"]){
							wpList.value[i]["count"] = data.data[j]["Cnt"]
							break;
						}
					}
				}  
				if(wpList.value[0]["count"] + wpList.value[1]["count"] >= 30){
					reviewfirst.value = true;
				} 
			});
		}
	}


	watch(() => props.lessonUuid, (nVal : string) => {
		if (nVal !== LessonUUID.value) {
			LessonUUID.value = nVal;
			initData();
		}
	})

	onLoad((query : any) => {

		if (query.LessonId) {
			LessonUUID.value = query.LessonId;
		}
		isReview.value = query.isreview == 1 ? true : false;
		// console.log(isReview.value);
		if (query.Type) {
			Type.value = query.Type;
		}

	})

	onMounted(() => {
		console.log('onMounted')
		initRole();
		initData();
	})
</script>

<style lang="scss" scoped>
	.content-box {
		--font-color: #332c2b;
		display: flex;
		flex-flow: column;
		flex: 1;
		padding-bottom: 50rpx;
		background-color: #eee;

		.detail-info {
			display: flex;
			flex-flow: column;
			flex: 1;
			padding-left: 10rpx;
			padding-right: 10rpx;
		}

		.detail {
			flex: 1;

		}
	}

	.up {
		color: #C06E7A;
	}

	.down {
		color: #3CA692;
	}

	.next-btn {
		/* #ifdef H5 */
		height: 45px !important;
		/* #endif */
	}

	.next-text {
		font-size: var(--text-16);
		font-weight: bold;
		display: flex;
	}

	/* 针对 1280px 分辨率 */
	@media(min-width:1200px) {
		.content-box {
			width: 2400rpx;
			margin: 0 auto !important;
		}

		.process {
			min-width: 238rpx;
		}

		.detail {}
	}
</style>